﻿using rpc_service.cache;

namespace rpc_service.core.support.assembly.roslyn.handle;

public class RoslynTypeHandle
{
    public string Handle(Type type)
    {
        return handleType(type.ToString());
    }

    private string handleType(string typeSignature)
    {
        // 拥有这个代表你一定是泛型对象
        if (typeSignature.Contains("`"))
        {
            int backtickIndex = typeSignature.IndexOf('`');
            int bracketIndex = typeSignature.IndexOf('[');
            int closeBracketIndex = typeSignature.LastIndexOf(']');
            
            if (backtickIndex >= 0 && bracketIndex >= 0 && closeBracketIndex >= 0)
            {
                string baseTypeName = typeSignature.Substring(0, backtickIndex);
                string genericArgs = typeSignature.Substring(bracketIndex + 1, closeBracketIndex - bracketIndex - 1);
                
                // 处理多个泛型参数的情况
                string[] args = genericArgs.Split(',');

                for (int i = 0; i < args.Length; i++)
                {
                    args[i] = handleType(args[i].Trim());
                }
                
                return $"{baseTypeName}<{string.Join(", ", args)}>";
            }
        }
        
        return typeSignature;
    }
    
    public bool IsBasicType(Type type)
    {
        return type.IsPrimitive ||
               type == "string".GetTypeByStr() ||
               type == "decimal".GetTypeByStr() ||
               type == "DateTime".GetTypeByStr() ||
               type == "Guid".GetTypeByStr() ||
               type == "TimeSpan".GetTypeByStr() ||
               type == "DateTimeOffset".GetTypeByStr() ||
               type.IsEnum;
    }
}